﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using VideoSystem;

namespace VideoSystem.Model
{
    public class Push
    {
        public void StartPush(List<User> users, Option option)
        {
            //implement!
            //string devId1 = "APA91bEDMFHlhhmfCW39s2DEfYRUByj46GWvQA2l7rAsOuu_5-4LScE7WeDnWeSGuQ2YqCSJ6PCLNjLGv5MU5QGBZGELoR9BDhtwKBA2_MKiI_LPqJUvk6G-f49Z6xmFtbVziGI8HDz8pbyM8hD8lhmHs047ys8qtQ";
            //string devId2 = "APA91bHX47YPuvsycq5I1YsJB6PkaeIrRYypclscuG8WW3-xGKFoY64jwyJ4F1feASIluy6V1an1CM7sVXxQYZv8xPcTRXCucmqCfpuQpr7KzN2OWV6B_vxdwsv7Eu7sw1t0AwxUElE6Dg0VvyDUet6lc_HPuPHOGA";
            //string devId3 = "APA91bFViPk90zeJc1fUXbGPCfeIDA_yEQy0fN0_UfoqLCZ22g_w_AfmxTCaNGFSIFsHeWOax8KaW6Pmm2R38eFR3lnaJa4pdArCo52ZpZvjEOW_-K_w_rG8_ESSQOuOC-bFB7LFEfuThvgo-hzln5is2bj9YXcXTA";
            //string devId4 = "APA91bH1a9umfAOYYRr4DJB-7bAMlGdh0npjke-ma7evIyBD1Ma6d-0PTbhv7pnAFE6_DIAkbBf3uW1WSUrShPpZLEgjf6HN_Yc7s6HlBE75kVX5jILwMWnj45YRVIe9IdmARQt5gnLIoUaVM8XtURoAcUeyXL0m1A";
            //IList<string> devIds = new List<string>();
       


            //if (IsPostBack)
            //{
            string BrowserAPIKey = "AIzaSyAKDK33hw5p6v-HQctSowAbuzv6Fy8hIrQ";
            string message = option.EpisodeId + ", " + option.Option1Text + ", " + option.Option2Text;
            Console.WriteLine(message);
            
            //string message = "1, Nissen taber huen!, Nissen taber ikke huen!";
            string tickerText = "example test GCM";
            string contentTitle = "content title GCM";
            
            for (int i = 0; i < users.Count; i++)
            {
            
                //string postData = "{ \"registration_ids\": [ \"" + tbRegistrationID.Text + "\" ], \"data\": {\"tickerText\":\"" + tickerText + "\", \"contentTitle\":\"" + contentTitle + "\", \"message\": \"" + message + "\"}}";
                string postData = "{ \"registration_ids\": [ \"" + users.ElementAt(i).userId + "\" ], \"data\": {\"tickerText\":\"" + tickerText + "\", \"contentTitle\":\"" + contentTitle + "\", \"message\": \"" + message + "\"}}";
                string response = SendGCMNotification(BrowserAPIKey, postData);

                //litResult.Text = response;
            }
        }

        /// <summary>
        /// Send a Google Cloud Message. Uses the GCM service and the provided api key.
        /// </summary>
        /// <param name="apiKey"></param>
        /// <param name="postData"></param>
        /// <param name="postDataContentType"></param>
        /// <returns>The response string from the google servers</returns>
        private static string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json")
        {
            // from here:
            // http://stackoverflow.com/questions/11431261/unauthorized-when-calling-google-gcm
            //
            // original:
            // http://www.codeproject.com/Articles/339162/Android-push-notification-implementation-using-ASP

            ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);

            //
            //  MESSAGE CONTENT
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            //
            //  CREATE REQUEST
            HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
            Request.Method = "POST";
            Request.KeepAlive = false;
            Request.ContentType = postDataContentType;
            Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
            Request.ContentLength = byteArray.Length;

            Stream dataStream = Request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            //
            //  SEND MESSAGE
            try
            {
                WebResponse Response = Request.GetResponse();
                HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
                if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
                {
                    var text = "Unauthorized - need new token";

                }
                else if (!ResponseCode.Equals(HttpStatusCode.OK))
                {
                    var text = "Response from web service isn't OK";
                }

                StreamReader Reader = new StreamReader(Response.GetResponseStream());
                string responseLine = Reader.ReadToEnd();
                Reader.Close();

                return responseLine;
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception in push:");
                Console.WriteLine(e);
            }
            return "error";
        }


        public static bool ValidateServerCertificate(
                                                  object sender,
                                                  X509Certificate certificate,
                                                  X509Chain chain,
                                                  SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
    }
}
